#!/usr/bin/env python
# encoding: utf-8

import codecs
import time
import tables
import os

try:
	import json
except ImportError:
	import simplejson as json

version = "1.6.1"

def safePrint(s):
	try:
		print s
	except UnicodeEncodeError: # it seems that when called from PHP, Python is unable to guess correctly the encoding of the standard output
		print s.encode("utf8")

class Common:
	
	def __init__(self, params):
		self.params = params
	
	def outputSuccessMessage(self,path):
		return _('Output file "%s" successfully generated.') % os.path.basename(path)
	
	def timeStamp(self):
		return _("Generated by Mocodo %s on %s") % (version,time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()))
	
	def loadInputFile(self):
		for encoding in self.params["encodings"]:
			try:
				self.encoding = encoding
				return codecs.open(self.params["dirRootExt"],encoding=encoding).read().replace('"','').split("\n")
			except UnicodeError:
				pass
		raise RuntimeError(("Mocodo Err.5 - " + _('Unable to read "%(file)s" with any of the following encodings: "%(encodings)s".') % {"file":self.params["dirRootExt"],"encodings":", ".join(self.params["encodings"])}).encode("utf8"))
	
	def loadStyle(self):
		style = {}
		style.update(json.loads(codecs.open("colors/%s.json" % self.params["colors"],"r","utf8").read()))
		style.update(json.loads(codecs.open("shapes/%s.json" % self.params["shapes"],"r","utf8").read()))
		style["attraction"] = self.params["attraction"]
		style[u"transparentColor"] = None
		return style
	
	def dumpOutputFile(self,result):
		path = "%(dirRoot)s-%(output)s.py" % self.params
		codecs.open(path,"w",encoding="utf8").write(result)
		safePrint(self.outputSuccessMessage(path))
	
	def dumpMldFiles(self, mcd):
		mldFormats = []
		for mldFormat in self.params["tables"]:
			try:
				mldFormats.append(json.loads(open("tables/%s.json" % mldFormat).read()))
			except:
				safePrint(_('Problem with format %s.') % mldFormat)
		t = tables.Tables(mcd)
		t.processAll()
		for mldFormat in mldFormats:
			path = self.params["dirRoot"] + mldFormat["extension"]
			try:
				text = t.getText(mldFormat)
				safePrint(self.outputSuccessMessage(path))
			except:
				text = _("Problem during MLD generation.")
				safePrint(text)
			codecs.open(os.path.join(path),"w",encoding="utf8").write(text)
	
	def prettyDict(self,name,l):
		if l:
			s = "%-"+str(max(len(k) for (k,_) in l)+3)+"s"
			return ["%s = {\n\t%s\n}" % (name,"\n\t".join(["%s: %s," % (s % ('u"%s"' % k),("%4d" % v if type(v) is int else ("% .2f" % v if type(v) is float else repr(v)))) for (k,v) in l]))]
		return []
	
	def dumpGeoFile(self,d):
		try:
			path = "%(dirRoot)s-geo.json" % self.params
			open(path,"w").write(json.dumps(d))
			safePrint(self.outputSuccessMessage(path))
		except IOError:
			safePrint(_('Unable to generate file "%s"!') % os.path.basename(path))
	
	def processGeometry(self,mcd,style):
		l = [
			("size",(mcd.w,mcd.h)),
			("cx",[(box.name,box.x+box.w/2) for row in mcd.ordering for box in row]),
			("cy",[(box.name,box.y+box.h/2) for row in mcd.ordering for box in row]),
			("k",[(leg.identifier(),leg.value()) for row in mcd.ordering for box in row for leg in box.legs]),
			("t",[(leg.identifier(),0.5) for row in mcd.ordering for box in row for leg in box.legs if leg.arrow]),
			("colors",[((c,style[c]) if style[c] else (c,None)) for c in sorted(style.keys()) if c.endswith("Color")]),
		]
		if self.params.get("extract",False):
			self.dumpGeoFile(dict(l))
			result = ["""try:\n\timport json\nexcept ImportError:\n\timport simplejson as json\n\ngeo = json.loads(open("%(root)s-geo.json").read())""" % self.params]
			result.append("""(width,height) = geo.pop("size")""")
			result.append("""for (name,l) in geo.iteritems(): globals()[name] = dict(l)""")
		else:
			result = ["(width,height) = (%s,%s)" % l[0][1]]
			for (k,v) in l[1:]:
				result.extend(self.prettyDict(k,v))
		return result


		